package cfh.spring.data.simplejdbcdemo.repository;

import cfh.spring.data.simplejdbcdemo.domain.Foo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Repository
public class FooDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SimpleJdbcInsert simpleJdbcInsert;

    public void insertData() {
        Arrays.asList("b", "c").forEach(bar ->
                jdbcTemplate.update("insert into FOO(bar) values (?)", bar)
        );

        HashMap<String, String> row = new HashMap<>();
        row.put("BAR", "d");
        Number id = simpleJdbcInsert.executeAndReturnKey(row);
        log.error(" d.ID :{}", id.longValue());
    }

    public void listData() {
        log.error("count :{}", jdbcTemplate.queryForObject("select count(*) from FOO", Long.class));

        List<String> bars = jdbcTemplate.queryForList("select BAR from FOO", String.class);
        bars.forEach(bar -> log.error("bar : {}", bar));

        List<Foo> foos = jdbcTemplate.query("select * from FOO", new RowMapper<Foo>() {

            @Override
            public Foo mapRow(ResultSet set, int i) throws SQLException {
                return new Foo()
                        .setId(set.getLong(1))
                        .setBar(set.getString(2));
            }
        });
        foos.forEach(foo -> log.error("foo:{}", foo));
    }
}
